package org.andu.java_gobang.game;

import org.andu.java_gobang.config.WebSocketConfig;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class OnlineUserManager {
    //表示用户在游戏大厅的在线状态
    private ConcurrentHashMap<Integer, WebSocketSession> gameHall = new ConcurrentHashMap<>();

    //表示用户在游戏房间的在线状态
    private ConcurrentHashMap<Integer, WebSocketSession> gameRoom = new ConcurrentHashMap<>();

    //存储已连接玩家
    private ConcurrentHashMap<Integer,Boolean> allPlayers = new ConcurrentHashMap<>();

    // 在线人数统计
    private AtomicInteger onlineCount = new AtomicInteger(0);

    // 进入游戏大厅
    public void enterGameHall(int userId, WebSocketSession webSocketSession) {
        // 如果是新玩家，增加计数
        if (allPlayers.putIfAbsent(userId, true) == null) {
            onlineCount.incrementAndGet();
        }
        gameHall.put(userId, webSocketSession);
    }

    // 退出游戏大厅
    public void exitGameHall(int userId) {
        gameHall.remove(userId);
    }

    public WebSocketSession getFromGameHall(int userId) {
        return gameHall.get(userId);
    }

    // 进入游戏房间
    public void enterGameRoom(int userId, WebSocketSession webSocketSession) {
        gameHall.remove(userId);
        gameRoom.put(userId, webSocketSession);
        // 从大厅转移到房间不需要增减总数
    }

    // 退出游戏房间
    public void exitGameRoom(int userId) {
        gameRoom.remove(userId);
    }

    public WebSocketSession getFromGameRoom(int userId) {
        return gameRoom.get(userId);
    }

    //玩家完全退出系统
    public void completeExit(int userId) {
        //从所有容器中移出
        gameHall.remove(userId);
        gameRoom.remove(userId);
        if (allPlayers.remove(userId) != null) {
            onlineCount.decrementAndGet();
        }
    }

    // 获取总在线人数
    public int getOnlineCount() {
        return onlineCount.get();
    }

    // 获取所有游戏大厅中的会话
    public Collection<WebSocketSession> getAllGameHallSessions() {
        return gameHall.values();
    }
}
